package com.example.mywf.ui;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mywf.utils.HttpUtil;
import com.example.mywf.R;
import com.example.mywf.bean.WeatherBean;
import com.google.gson.Gson;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class WeatherActivity extends AppCompatActivity implements View.OnClickListener {
    //定义对象
    private WeatherBean weatherBean;
    private WeatherBean.CityInfoDTO cityInfoDTO;
    private WeatherBean.DataDTO dataDTO;
    private List<WeatherBean.DataDTO.ForecastDTO> forecastDTOList;
    private static String httpString = "http://t.weather.itboy.net/api/weather/city/";
    private String cityId = "101280101";
    private String json;
    private TodayFragment todayFragment;
    private ForecastFragment forecastFragment;
    private Bundle bundle;
    private AnimationDrawable animation;
    //定义控件
    private ImageView background_iv;
    private TextView time;
    private TextView city;
    private TextView type;
    private TextView wendu;
    private TextView high;
    private TextView low;
    private Button forecast_btn;
    private Button today_btn;
    private ImageButton more_btn;
    //创建线程池
    private ExecutorService threadPool = new ThreadPoolExecutor(
            2,//默认核心线程池大小
            Runtime.getRuntime().availableProcessors(),//最大核心线程池大小，模拟器是4核
            30,//超时等待时间，没人调用就释放
            TimeUnit.SECONDS,//超时时间单位
            new LinkedBlockingDeque<>(2),//阻塞队列，最大可排队等待的线程个数
            Executors.defaultThreadFactory(),//线程工厂，创建线程
            new ThreadPoolExecutor.DiscardOldestPolicy()//拒绝策略，尝试竞争老的线程
    );
    //创建map缓存信息，线程安全，解决java.util.ConcurrentModificationException并发修改异常
    private Map<String, JsonAndTime> jsonMap = new ConcurrentHashMap<>();
    //线程不安全
//    private Map<String, JsonAndTime> jsonMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载界面布局
        setContentView(R.layout.activity_main);
        //初始化控件
        initView();
        //获取json信息
        getJson(cityId);
    }

    // 主线程创建消息处理器
    private final Handler handler = new Handler(Looper.myLooper()) {
        public void handleMessage(android.os.Message msg) {
            //200则成功
            if (msg.what == 200) {
                //接收线程获取的资源
                json = (String) msg.obj;
                //gson解析获取对象
                gsonObject();
                //显示天气数据
                showData();
                //执行今日天气点击
                today_btn.performClick();
                //0则失败
            } else if (msg.what == 0) {
                Toast.makeText(WeatherActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
            }
        }
    };

    //初始化控件
    private void initView() {
        background_iv = findViewById(R.id.background_iv);
        time = findViewById(R.id.time_tv);
        city = findViewById(R.id.city_tv);
        type = findViewById(R.id.type_today_tv);
        wendu = findViewById(R.id.wendu_tv);
        high = findViewById(R.id.high_today_tv);
        low = findViewById(R.id.low_today_tv);
        forecast_btn = findViewById(R.id.forecast_btn);
        today_btn = findViewById(R.id.today_btn);
        more_btn = findViewById(R.id.more_btn);
        //设置按钮点击事件
        forecast_btn.setOnClickListener(this);
        today_btn.setOnClickListener(this);
        more_btn.setOnClickListener(this);
    }

    //获取json信息
    private void getJson(String cityId) {
        //创建消息
        Message message = new Message();
        //判断是否有缓存
        if (jsonMap.containsKey(cityId)) {
            //判断时间戳是否相差30000ms即30s
            if (System.currentTimeMillis() - jsonMap.get(cityId).getCurrentTime() <= 30000) {
                //如果30s内有获取过，则取出使用
                String myJson = jsonMap.get(cityId).getJson();
                //设置消息类型
                message.what = 200;
                //设置传送的数据
                message.obj = myJson;
                //发送消息到消息队里进行下一步操作
                handler.sendMessage(message);
                //返回，结束方法
                return;
            }
        }
        //处理得到url
        String urlString = httpString + cityId;
        //通过线程池开启线程获取天气信息
        threadPool.execute(() -> {
            //通过网络资源获取json数据
            String myJson = HttpUtil.getJsonInfo(urlString);
            //如果资源获取成功
            if (myJson != null) {
                System.out.println("请求成功");
                //存入map中
                jsonMap.put(cityId, new JsonAndTime(System.currentTimeMillis(), myJson));
                System.out.println(jsonMap);
                System.out.println(jsonMap.get(cityId).toString());
                //调用自身再次尝试获取json数据
                getJson(cityId);
            } else {
                System.out.println("请求失败");
                //设置消息类型
                message.what = 0;
                //设置传送的数据
                message.obj = null;
                //发送消息到消息队里进行下一步操作
                handler.sendMessage(message);
            }
        });
    }

    //gson解析
    private void gsonObject() {
        //创建gson对象
        Gson gson = new Gson();
        //gson解析获得weatherBean对象
        weatherBean = gson.fromJson(json, WeatherBean.class);
        //从weatherBean对象中获取cityInfo对象
        cityInfoDTO = weatherBean.getCityInfo();
        //从weatherBean对象中获取data对象
        dataDTO = weatherBean.getData();
        //获取forcast列对象
        forecastDTOList = weatherBean.getData().getForecast();
    }

    //显示天气数据
    private void showData() {
        time.setText(weatherBean.getTime());
        city.setText(cityInfoDTO.getCity());
        type.setText(forecastDTOList.get(0).getType());
        wendu.setText(dataDTO.getWendu());
        high.setText(forecastDTOList.get(0).getHigh());
        low.setText(forecastDTOList.get(0).getLow());
        //设置背景
        setBackground();
    }

    //设置天气背景
    private void setBackground() {
        background_iv.setBackgroundResource(R.drawable.duoyun_day);
        if (animation != null) {
            animation.stop();
            animation = null;
        }
        switch (forecastDTOList.get(0).getType()) {
            case "暴雨":
                background_iv.setBackgroundResource(R.drawable.baoyu_frame);
                animation = (AnimationDrawable) background_iv.getBackground();
                animation.start();
                break;
            case "雷阵雨":
                background_iv.setBackgroundResource(R.drawable.baoyu_frame);
                animation = (AnimationDrawable) background_iv.getBackground();
                animation.start();
                break;
            case "大雨":
                background_iv.setBackgroundResource(R.drawable.dayu_frame);
                animation = (AnimationDrawable) background_iv.getBackground();
                animation.start();
                break;
            case "中雨":
                background_iv.setBackgroundResource(R.drawable.dayu_frame);
                animation = (AnimationDrawable) background_iv.getBackground();
                animation.start();
                break;
            case "小雨":
                background_iv.setBackgroundResource(R.drawable.xiaoyu_frame);
                animation = (AnimationDrawable) background_iv.getBackground();
                animation.start();
                break;
            case "阵雨":
                background_iv.setBackgroundResource(R.drawable.xiaoyu_frame);
                animation = (AnimationDrawable) background_iv.getBackground();
                animation.start();
                break;
            case "多云":
                background_iv.setBackgroundResource(R.drawable.duoyun_day);
                break;
            case "阴":
                background_iv.setBackgroundResource(R.drawable.yin_day);
                break;
            case "晴":
                background_iv.setBackgroundResource(R.drawable.duoyun_day);
                break;
        }
    }

    //按钮点击事件，显示不同的fragment
    @Override
    public void onClick(View v) {
        //更多按钮的点击事件
        if (v.getId() == R.id.more_btn) {
            //创建意图
            Intent intent = new Intent(WeatherActivity.this, CityActivity.class);
            //打开新页面
            startActivityForResult(intent, 1);
            //其他按钮的点击事件，如果有数据，才进行
        } else if (json != null) {
            //获取fragment管理
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            //创建一个bundle
            bundle = new Bundle();
            //放入数据
            bundle.putString("json", json);
            //判断按钮
            switch (v.getId()) {
                case R.id.forecast_btn:
                    //创建新的fragment
                    forecastFragment = new ForecastFragment();
                    //传递bundle
                    forecastFragment.setArguments(bundle);
                    //替换fragment
                    transaction.replace(R.id.fragment_container, forecastFragment);
                    break;
                case R.id.today_btn:
                    //创建新的fragment
                    todayFragment = new TodayFragment();
                    //传递bundle
                    todayFragment.setArguments(bundle);
                    //替换fragment
                    transaction.replace(R.id.fragment_container, todayFragment);
                    break;
                default:
                    break;
            }
            //提交
            transaction.commitAllowingStateLoss();
        } else {
            //否则提示没有网络
            Toast.makeText(WeatherActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
            //尝试获取json数据
            getJson(cityId);
        }
    }

    //页面返回后处理信息
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == 1) {
                if (requestCode == 1) {
                    try {
                        //取出返回的城市id
                        cityId = data.getStringExtra("cityid");
                        //获取json数据
                        getJson(cityId);
                    } catch (Exception e) {
                        System.out.println("没数据");
                    }
                }
            }
        }
    }
}

//辅助存放实体类
class JsonAndTime {
    private Long currentTime;
    private String json;

    public JsonAndTime(Long currentTime, String json) {
        this.currentTime = currentTime;
        this.json = json;
    }

    public Long getCurrentTime() {
        return currentTime;
    }

    public void setCurrentTime(Long currentTime) {
        this.currentTime = currentTime;
    }

    public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }

    @Override
    public String toString() {
        return "JsonAndTime{" +
                "currentTime=" + currentTime +
                ", json='" + json + '\'' +
                '}';
    }
}